import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*

log.info "dbreader"

response.setContentType("text/html; charset=UTF-8")
response.setCharacterEncoding("UTF-8")




String urlString = request.getParameter("url")

def metaDataQuery = new Query("metadata")
metaDataQuery.addFilter("rssUrl", Query.FilterOperator.EQUAL, urlString)
PreparedQuery preparedQuery3 = datastore.prepare(metaDataQuery)
def metaDataEntities = preparedQuery3.asList(withLimit(1))

if (metaDataEntities.size() > 0) {

    def metaDataEntity = metaDataEntities[0]
    request.setAttribute 'header', metaDataEntity.headerFile
    String blogg = metaDataEntity.entityName
    log.info "blogg to load " + blogg
    log.info "categories to load " + metaDataEntity.categoriesEntityName

    if (metaDataEntity.categoriesEntityName) {
        def metaQuery = new Query(metaDataEntity.categoriesEntityName)
        PreparedQuery preparedQuery2 = datastore.prepare(metaQuery)

        // return only the first 10 results
        def categories = preparedQuery2.asList(withLimit(50))
        categories.each {
            //log.info it.toString()
        }
        request.setAttribute 'categories', categories
    }

//String blogg = request.getParameter("blogg")
    String category = request.getParameter("category")
    if (blogg) {

// query the scripts stored in the datastore
// "savedscript" corresponds to the entity table containing the scripts' text
        def query = new Query(blogg)

// sort results by descending order of the creation date
        query.addSort("updated", Query.SortDirection.DESCENDING)

// filters the entities so as to return only scripts by a certain author
        if (category && !category.equals("latest")) {
            log.info "URLDecoder.decode(category)= "+URLDecoder.decode(category,"UTF-8")
            query.addFilter("category", Query.FilterOperator.EQUAL, URLDecoder.decode(category,"UTF-8"))
        }

        PreparedQuery preparedQuery = datastore.prepare(query)

// return only the first 10 results
        def entities = preparedQuery.asList(withLimit(50))

        request.setAttribute 'entities', entities

//request.setAttribute 'body', mresponse.content
        forward '/WEB-INF/pages/blog.gtpl'
    }
    else {
        out.println "missing param blogg"
    }
}
